from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


def generate_save_user_token(openid):
    """
    使用itsdangerous保存openid，生成access_token
    :param openid:
    :return:
    """
    serializer = Serializer(settings.SECRET_KEY, 300)

    data = {'openid': openid}
    token = serializer.dumps(data)
    return token


def check_save_user_token(access_token):
    """
    使用itsdangerous提取access_token中的openid
    :param access_token:
    :return:
    """
    # serializer = Serializer(密钥，有效时间秒)
    serializer = Serializer(settings.SECRET_KEY, 300)
    try:
        data = serializer.loads(access_token)
    except BadData:
            #验证失败，会抛出itsdangerous.baddata异常
        return None
    else:
        # 校验成功，返回access_token中的openid
        return data['openid']
